package nongchang.kuaijiecaifu.com.ncapp_android.ui.fragment;

import android.content.Context;
import android.os.Bundle;
import android.support.design.widget.TabLayout;
import android.support.v7.app.AlertDialog;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.StaggeredGridLayoutManager;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.AccelerateInterpolator;
import android.view.animation.Animation;
import android.view.animation.AnimationSet;
import android.view.animation.LinearInterpolator;
import android.view.animation.TranslateAnimation;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import nongchang.kuaijiecaifu.com.ncapp_android.Const;

import nongchang.kuaijiecaifu.com.ncapp_android.R;
import nongchang.kuaijiecaifu.com.ncapp_android.common.fragment.BaseFragment;
import nongchang.kuaijiecaifu.com.ncapp_android.retrofit.data.ChildCartManager;
import nongchang.kuaijiecaifu.com.ncapp_android.retrofit.data.HomeCartManager;
import nongchang.kuaijiecaifu.com.ncapp_android.retrofit.good.AllCart;
import nongchang.kuaijiecaifu.com.ncapp_android.retrofit.good.BasketMenu;
import nongchang.kuaijiecaifu.com.ncapp_android.retrofit.good.BasketType;

import nongchang.kuaijiecaifu.com.ncapp_android.retrofit.good.HomeItemCart;
import nongchang.kuaijiecaifu.com.ncapp_android.ui.adapter.basketadapter.BasketCartAdapter;
import nongchang.kuaijiecaifu.com.ncapp_android.ui.adapter.basketadapter.BasketMenuAdapter;
import nongchang.kuaijiecaifu.com.ncapp_android.ui.adapter.basketadapter.BasketTypeAdapter;


/**
 * Created by Administrator on 2016/6/6 0006.
 */
public class VegetableBasketFragment extends BaseFragment {
    @BindView(R.id.list1)
    RecyclerView list1;
    @BindView(R.id.list2)
    RecyclerView list2;
    @BindView(R.id.list3)
    RecyclerView list3;
    @BindView(R.id.sign_view)
    View signView;

    private BasketMenuAdapter menuAdapter;
    private BasketTypeAdapter typeAdapter;
    private BasketCartAdapter cartAdapter;
    private int screenHeight = 0;
    private int screenWidth = 0;
    //软件盘弹起后所占高度阀值
    private int keyHeight = 0;
    private int keyWidth = 0;
    private RecyclerView.AdapterDataObserver sumObserver = new RecyclerView.AdapterDataObserver() {

        @Override
        public void onChanged() {
            super.onChanged();
            //执行相应的操作
            float sum = 0;
            for (int i = 0; i < HomeCartManager.cartList.size(); i++) {
                sum += HomeCartManager.cartList.get(i).money;
            }
        }
    };

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View view = inflater.inflate(R.layout.fragment_vegetable_basket, container, false);
        return view;
    }

    @Override
    public void onViewCreated(View view, Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        ButterKnife.bind(this, getView());
        screenHeight = getActivity().getWindowManager().getDefaultDisplay().getHeight();
        screenWidth = getActivity().getWindowManager().getDefaultDisplay().getWidth();
        //阀值设置为屏幕高度的1/3
        keyHeight = screenHeight / 3;
        keyWidth = (int) (screenWidth * 0.6);
        setFristListView();
        setSecondListView();
        setThirdListView();
    }

    private void setThirdListView() {
        cartAdapter = new BasketCartAdapter(getContext());
        list3.setAdapter(cartAdapter);
        cartAdapter.registerAdapterDataObserver(sumObserver);
        setCartListener();
//        loadMultipleCart();
        loadCart();
    }

    private ImageView buyImg;//
    private AllCart item;

    private void setUpdate(int position) {
        item = null;
        item = new AllCart();
        item.isSelect = true;
        item.unitId = HomeCartManager.cartList.get(position).unitId;
        item.one_money = HomeCartManager.cartList.get(position).one_money;
        item.money = HomeCartManager.cartList.get(position).money;
        item.number = HomeCartManager.cartList.get(position).number;
        item.type = 2;
        HomeCartManager.local.add(item);
    }

    private void setNotUpdate(int position) {
        item = null;
        item = new AllCart();
        item.isSelect = true;
        item.unitId = HomeCartManager.cartList.get(position).unitId;
        item.one_money = HomeCartManager.cartList.get(position).one_money;
        item.money = HomeCartManager.cartList.get(position).money;
        item.number = HomeCartManager.cartList.get(position).number;
        item.type = 2;
    }

    private void setCartListener() {
        cartAdapter.setOnAddNum(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                int[] start_location = new int[2];
                v.getLocationInWindow(start_location);
                buyImg = new ImageView(getContext());
                buyImg.setImageResource(R.drawable.sign);
                setAnim(buyImg, start_location);
                Object tag = v.getTag();

                if (tag != null && tag instanceof Integer) { //解决问题：如何知道你点击的按钮是哪一个列表项中的，通过Tag的position
                    int position = (Integer) tag;
                    int num = HomeCartManager.cartList.get(position).number;
                    num++;
                    HomeCartManager.cartList.get(position).number = num; //修改集合中商品数量
                    HomeCartManager.cartList.get(position).money = (HomeCartManager.cartList.get(position).one_money * num); //修改集合中该商品总价 数量*单价
                    //解决问题：点击某个按钮的时候，如果列表项所需的数据改变了，如何更新UI
                    cartAdapter.update(HomeCartManager.cartList);
                    setUpdate(position);
                }

            }
        });
        cartAdapter.setOnSubNum(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Object tag = v.getTag();
                if (tag != null && tag instanceof Integer) { //解决问题：如何知道你点击的按钮是哪一个列表项中的，通过Tag的position
                    int position = (Integer) tag;
                    int num = HomeCartManager.cartList.get(position).number;
                    if (num <= 0) {
                        return;
                    }
                    num--;
                    HomeCartManager.cartList.get(position).number = num; //修改集合中商品数量
                    HomeCartManager.cartList.get(position).money = (HomeCartManager.cartList.get(position).one_money * num); //修改集合中该商品总价 数量*单价
                    //解决问题：点击某个按钮的时候，如果列表项所需的数据改变了，如何更新UI
                    cartAdapter.update(HomeCartManager.cartList);
                    if (num == 0) {
                        HomeCartManager.local.remove(HomeCartManager.cartList.get(position).unitId);
                    } else {
                        setUpdate(position);
                    }
                }
            }
        });
        cartAdapter.setOnTotalNum(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                if (hasFocus) {
                    Object tag = v.getTag();
                    ((EditText) v).addTextChangedListener(new TextWatcher() {
                        @Override
                        public void beforeTextChanged(CharSequence s, int start, int count, int after) {

                        }

                        @Override
                        public void onTextChanged(CharSequence s, int start, int before, int count) {

                        }

                        @Override
                        public void afterTextChanged(Editable s) {
                            if (list3.isComputingLayout()) {
                                return;
                            }
                            if (s.toString().equals("")) {
                                ((EditText) v).setText("0");
                                if (tag != null && tag instanceof Integer) {
                                    int position = (Integer) tag;
                                    HomeCartManager.cartList.get(position).number = 0;
                                    HomeCartManager.cartList.get(position).money = (HomeCartManager.cartList.get(position).one_money * 0);
                                    HomeCartManager.local.remove(HomeCartManager.cartList.get(position).unitId);
                                }
                            } else {
                                if (tag != null && tag instanceof Integer) {
                                    int position = (Integer) tag;
                                    HomeCartManager.cartList.get(position).number = Integer.parseInt(((EditText) v).getText().toString());
                                    HomeCartManager.cartList.get(position).money = (HomeCartManager.cartList.get(position).one_money * HomeCartManager.cartList.get(position).number);
                                    setNotUpdate(position);
                                }
                            }
                        }
                    });
                } else {
                    if (list3.isComputingLayout()) {
                        return;
                    }
                    cartAdapter.update(HomeCartManager.cartList);
                }
            }
        }, new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                if (actionId == EditorInfo.IME_ACTION_DONE
                        || (event != null && event.getKeyCode() == KeyEvent.KEYCODE_ENTER)) {
                    //do something;
                    list3.requestFocus();
                    InputMethodManager imm = (InputMethodManager)
                            getActivity().getSystemService(Context.INPUT_METHOD_SERVICE);
                    imm.hideSoftInputFromWindow(v.getWindowToken(), 0);
                    return true;
                }
                return false;
            }
        });
    }

    private void loadMultipleCart() {
        List<AllCart> list = new ArrayList<>();
        AllCart product = null;
        for (int i = 1; i <= 10; i++) {
            product = new AllCart();
            product.one_money = 1;
            product.unitId = "product" + i;
            product.number = 0;
            product.weight = 5;
            product.type = 1;
            product.title = "特价手机";
            switch (i) {
                case 0:
                    product.image = "https://g-search1.alicdn.com/img/bao/uploaded/i4/TB1Mc9aQVXXXXb6XVXXXXXXXXXX.jpg_180x180.jpg_.webp";
                    break;
                case 1:
                    product.image = "https://g-search3.alicdn.com/img/bao/uploaded/i4/TB1dn5CQVXXXXaTXpXXXXXXXXXX.jpg_180x180.jpg_.webp";
                    break;
                case 2:
                    product.image = "https://g-search1.alicdn.com/img/bao/uploaded/i4/TB1to7LQFXXXXcdXXXXXXXXXXXX.jpg_180x180.jpg_.webp";
                    break;
                case 3:
                    product.image = "https://g-search1.alicdn.com/img/bao/uploaded/i4/TB1my7dQVXXXXaOXFXXXXXXXXXX.jpg_180x180.jpg_.webp";
                    break;
                case 4:
                    product.image = "https://g-search1.alicdn.com/img/bao/uploaded/i4/TB1QIwIOXXXXXXvaXXXXXXXXXXX.jpg_180x180.jpg_.webp";
                    break;
                default:
                    product.image = "https://g-search2.alicdn.com/img/bao/uploaded/i4/TB1R8uxOFXXXXccXXXXXXXXXXXX.jpg_180x180.jpg_.webp";

            }
            product.money = 0;
            list.add(product);
        }
        cartAdapter.update(list);
    }

    private void loadCart() {
        List<AllCart> list = new ArrayList<>();
        AllCart product = null;
        for (int i = 1; i <= 10; i++) {
            product = new AllCart();
            product.one_money = 1;
            product.unitId = "simpleproduct" + i;
            product.number = 0;
            product.weight = 5;
            product.type = 2;
            product.title = "手机";
            switch (i) {
                case 0:
                    product.image = "https://g-search1.alicdn.com/img/bao/uploaded/i4/TB1Mc9aQVXXXXb6XVXXXXXXXXXX.jpg_180x180.jpg_.webp";
                    break;
                case 1:
                    product.image = "https://g-search3.alicdn.com/img/bao/uploaded/i4/TB1dn5CQVXXXXaTXpXXXXXXXXXX.jpg_180x180.jpg_.webp";
                    break;
                case 2:
                    product.image = "https://g-search1.alicdn.com/img/bao/uploaded/i4/TB1to7LQFXXXXcdXXXXXXXXXXXX.jpg_180x180.jpg_.webp";
                    break;
                case 3:
                    product.image = "https://g-search1.alicdn.com/img/bao/uploaded/i4/TB1my7dQVXXXXaOXFXXXXXXXXXX.jpg_180x180.jpg_.webp";
                    break;
                case 4:
                    product.image = "https://g-search1.alicdn.com/img/bao/uploaded/i4/TB1QIwIOXXXXXXvaXXXXXXXXXXX.jpg_180x180.jpg_.webp";
                    break;
                default:
                    product.image = "https://g-search2.alicdn.com/img/bao/uploaded/i4/TB1R8uxOFXXXXccXXXXXXXXXXXX.jpg_180x180.jpg_.webp";
            }
            product.money = 0;
            list.add(product);
        }
        cartAdapter.update(list);
    }

    private void setSecondListView() {
        typeAdapter = new BasketTypeAdapter(getContext());
        list2.setAdapter(typeAdapter);
        loadType();
    }

    private void setFristListView() {
        list1.setLayoutManager(new StaggeredGridLayoutManager(1,
                StaggeredGridLayoutManager.HORIZONTAL));
        menuAdapter = new BasketMenuAdapter(getContext());
        list1.setAdapter(menuAdapter);
        load();
    }

    private List<BasketType> Typelist;

    private void loadType() {
        Typelist = new ArrayList<>();
        for (int i = 0; i < 2; i++) {
            BasketType item = new BasketType();
            if (i == 0) {
                item.isselect = true;
            }
            item.name = Const.BASK_TYPE[i];
            Typelist.add(item);
        }
        typeAdapter.update(Typelist);
        setTypeListener();
    }

    private void setTypeListener() {
        typeAdapter.setOnBackGround(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Object tag = v.getTag();
                if (tag != null && tag instanceof Integer) { //解决问题：如何知道你点击的按钮是哪一个列表项中的，通过Tag的position
                    int position = (Integer) tag;
                    for (int i = 0, size = Typelist.size(); i < size; i++) {
                        if (i == position) {
                            Typelist.get(i).isselect = true;
                            continue;
                        }
                        Typelist.get(i).isselect = false;
                    }
                    typeAdapter.update(Typelist);
                }
            }
        });
    }

    private List<BasketMenu> list;

    private void load() {
        list = new ArrayList<>();
        for (int i = 0; i < 6; i++) {
            BasketMenu item = new BasketMenu();
            if (i == 0) {
                item.isselect = true;
            }
            item.selectimage = Const.BASK_SELECT_RES[i];
            item.selectedimage = Const.BASK_SELECTED_RES[i];
            item.name = Const.BASK_NAME[i];
            list.add(item);
        }
        menuAdapter.update(list);
        setFirstListener();
    }

    private void setFirstListener() {
        menuAdapter.setOnBackGround(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Object tag = v.getTag();
                if (tag != null && tag instanceof Integer) { //解决问题：如何知道你点击的按钮是哪一个列表项中的，通过Tag的position
                    int position = (Integer) tag;
                    for (int i = 0, size = list.size(); i < size; i++) {
                        if (i == position) {
                            list.get(i).isselect = true;
                        } else {
                            list.get(i).isselect = false;
                        }

                    }
                    if (position == 0) {
//                        loadMultipleCart();
                        loadCart();
                    } else {
                        loadCart();
                    }
                    menuAdapter.update(list);
                }
            }
        });
    }


    private ViewGroup createAnimLayout() {
        ViewGroup rootView = (ViewGroup) getActivity().getWindow().getDecorView();
        LinearLayout animLayout = new LinearLayout(getContext());
        LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(
                LinearLayout.LayoutParams.MATCH_PARENT,
                LinearLayout.LayoutParams.MATCH_PARENT);
        animLayout.setLayoutParams(lp);
        animLayout.setId(R.id.mLayout);
        animLayout.setBackgroundResource(android.R.color.transparent);
        rootView.addView(animLayout);
        return animLayout;
    }

    private View addViewToAnimLayout(final ViewGroup vg, final View view,
                                     int[] location) {
        int x = location[0];
        int y = location[1];
        LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(
                LinearLayout.LayoutParams.WRAP_CONTENT,
                LinearLayout.LayoutParams.WRAP_CONTENT);
        lp.leftMargin = x;
        lp.topMargin = y;
        view.setLayoutParams(lp);
        return view;
    }

    private ViewGroup anim_mask_layout;

    private void setAnim(final View v, int[] start_location) {
        anim_mask_layout = null;
        anim_mask_layout = createAnimLayout();
        anim_mask_layout.addView(v);//�Ѷ���С����ӵ�������
        final View view = addViewToAnimLayout(anim_mask_layout, v,
                start_location);
        int[] end_location = new int[2];// ���������洢��������λ�õ�X��Y����
        signView.getLocationInWindow(end_location);// shopCart���Ǹ����ﳵ

        // ����λ��
        int endX = 0 - start_location[0] + keyWidth;// ����λ�Ƶ�X����
        int endY = end_location[1] - start_location[1];// ����λ�Ƶ�y����
        TranslateAnimation translateAnimationX = new TranslateAnimation(0,
                endX, 0, 0);
        translateAnimationX.setInterpolator(new LinearInterpolator());
        translateAnimationX.setRepeatCount(0);// �����ظ�ִ�еĴ���
        translateAnimationX.setFillAfter(true);

        TranslateAnimation translateAnimationY = new TranslateAnimation(0, 0,
                0, endY);
        translateAnimationY.setInterpolator(new AccelerateInterpolator());
        translateAnimationY.setRepeatCount(0);// �����ظ�ִ�еĴ���
        translateAnimationX.setFillAfter(true);

        AnimationSet set = new AnimationSet(false);
        set.setFillAfter(false);
        set.addAnimation(translateAnimationY);
        set.addAnimation(translateAnimationX);
        set.setDuration(800);// ������ִ��ʱ��
        view.startAnimation(set);
        // ���������¼�
        set.setAnimationListener(new Animation.AnimationListener() {
            // �����Ŀ�ʼ
            @Override
            public void onAnimationStart(Animation animation) {
                v.setVisibility(View.VISIBLE);
            }

            @Override
            public void onAnimationRepeat(Animation animation) {
                // TODO Auto-generated method stub
            }

            // �����Ľ���
            @Override
            public void onAnimationEnd(Animation animation) {
                v.setVisibility(View.GONE);
            }
        });
    }


    @Override
    public void onResume() {
        super.onResume();
        list3.addOnLayoutChangeListener(new View.OnLayoutChangeListener() {
            @Override
            public void onLayoutChange(View v, int left, int top, int right, int bottom, int oldLeft, int oldTop, int oldRight, int oldBottom) {
                if (oldBottom != 0 && bottom != 0 && (oldBottom - bottom > keyHeight)) {

//                    Toast.makeText(CartActivity.this, "监听到软键盘弹起...", Toast.LENGTH_SHORT).show();

                } else if (oldBottom != 0 && bottom != 0 && (bottom - oldBottom > keyHeight)) {
//                    Toast.makeText(CartActivity.this, "监听到软件盘关闭...", Toast.LENGTH_SHORT).show();
                    list3.post(new Runnable() {
                        @Override
                        public void run() {
                            list3.requestFocus();
                        }
                    });
                }
            }
        });
    }
}
